<?php
/**
 * Created by PhpStorm.
 * User: ybjaa
 * Date: 2017/5/4
 * Time: 10:14
 */

namespace App\Business\Menu;

use App\Business\BusBase;
use App\Business\Model\Menu;

abstract class MenusBase extends BusBase
{


    /**
     * 菜单按数型排序
     * @param array $menus
     * @return array
     */
    protected function menuSort(Array $menus)
    {

        if(!$menus||count($menus)<=0) return [];

        $length=count($menus);

        $menus=array_combine(array_map(function($arr){return $arr->nextID;},$menus),$menus);

        $newMenus=[];

        if(!key_exists("",$menus)) return [];

        $newMenus[]=$menus[null];


        while (key_exists($newMenus[count($newMenus)-1]->ID,$menus))
            $newMenus[]=$menus[$newMenus[count($newMenus)-1]->ID];

        return array_reverse($newMenus);


    }



    protected function recursion(Array $arr1,Array $all)
    {


        foreach ($arr1 as $a)
        {
            $childrenMenus=array_filter($all,function(Menu $m)use($a){
                return $m->parentID===$a->ID;
            });

            if($childrenMenus===null||count($childrenMenus)<=0) continue;

            $a->children= array_values($this->menuSort($childrenMenus));
            $this->recursion(array_values($childrenMenus),$all);

        }
    }





}